/*
 * Tencent is pleased to support the open source community by making ovCompose available.
 * Copyright (C) 2025 THL A29 Limited, a Tencent company. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.tencent.compose.video

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Divider
import androidx.compose.material.Icon
import androidx.compose.material.Tab
import androidx.compose.material.TabRow
import androidx.compose.material.TabRowDefaults
import androidx.compose.material.TabRowDefaults.tabIndicatorOffset
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.filled.ThumbUp
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
// 视频缩略图数据
data class EpisodeThumbnail(
    val id: String,
    val date: String,
    val title: String,
    val imageUrl: String,
    val isVip: Boolean = false,
    val isPlaying: Boolean = false
)

@Composable
internal fun VideoDetailPage(
    video: VideoItem,
    onBack: () -> Unit
) {
    var selectedTab by remember { mutableStateOf(0) }
    var selectedSeason by remember { mutableStateOf("第7季") }
    var selectedViewMode by remember { mutableStateOf("正片") }
    var selectedBottomTab by remember { mutableStateOf("全部") }

    val tabs = listOf("详情", "讨论")
    val seasons = listOf("第3季", "第4季", "精编版", "第5季", "第6季", "第7季")
    val viewModes = listOf("正片", "纯享", "竖屏", "陪看", "直播回放")
    val bottomTabs = listOf("全部", "本期看点", "精彩花絮")

    // 模拟推荐数据
    val recommendations = remember {
        listOf(
            VideoItem("r1", "令人心动的offer 第7季：职场新人成长记", "陈铭 时代少年团贺峻霖 职场节目 实习生们的真实职场挑战与成长故事", "", imageUrl = "https://picsum.photos/400/300?random=50"),
            VideoItem("r2", "奔跑吧兄弟 第12季：兄弟团再出发", "邓超 陈赫 李晨 综艺真人秀 全新挑战任务等你来看", "", imageUrl = "https://picsum.photos/400/300?random=51"),
            VideoItem("r3", "极限挑战 第9季：挑战极限再升级", "黄渤 孙红雷 张艺兴 挑战极限 更多精彩任务等你解锁", "", imageUrl = "https://picsum.photos/400/300?random=52"),
            VideoItem("r4", "向往的生活 第8季：慢生活新体验", "何炅 黄磊 慢生活综艺 远离城市喧嚣享受田园时光", "", imageUrl = "https://picsum.photos/400/300?random=53"),
            VideoItem("r5", "中国好声音 第15季：音乐梦想再起航", "周杰伦 那英 音乐选秀 寻找下一个音乐天才", "", imageUrl = "https://picsum.photos/400/300?random=54"),
            VideoItem("r6", "这就是街舞 第6季：舞者巅峰对决", "易烊千玺 韩庚 街舞竞技 最燃的街舞battle现场", "", imageUrl = "https://picsum.photos/400/300?random=55"),
            VideoItem("r7", "明星大侦探 第9季：烧脑推理再升级", "何炅 撒贝宁 推理悬疑 层层递进的悬疑案件等你破解", "", imageUrl = "https://picsum.photos/400/300?random=56"),
            VideoItem("r8", "创造营2024：青春梦想舞台", "选秀综艺 青春励志 见证偶像的诞生与成长", "", imageUrl = "https://picsum.photos/400/300?random=57"),
            VideoItem("r9", "乘风破浪的姐姐 第5季：30+女星成团", "30+女星 成团竞演 展现成熟女性的魅力与实力", "", imageUrl = "https://picsum.photos/400/300?random=58"),
            VideoItem("r10", "披荆斩棘的哥哥 第4季：男星成团挑战", "30+男星 成团竞演 展现成熟男性的魅力与才华", "", imageUrl = "https://picsum.photos/400/300?random=59"),
            VideoItem("r11", "王牌对王牌 第8季：搞笑综艺再升级", "沈腾 贾玲 搞笑综艺 更多爆笑场面等你来看", "", imageUrl = "https://picsum.photos/400/300?random=60"),
            VideoItem("r12", "青春环游记 第5季：旅行真人秀", "旅行真人秀 青春活力 跟着明星一起环游世界", "", imageUrl = "https://picsum.photos/400/300?random=61"),
            VideoItem("r13", "中餐厅 第8季：美食经营文化传播", "美食经营 文化传播 在异国他乡经营中餐厅的故事", "", imageUrl = "https://picsum.photos/400/300?random=62"),
            VideoItem("r14", "四喜·活宝爹妈：家庭喜剧", "薛甄珠终于加上闺女微信了 家庭生活中的温馨与搞笑", "", imageUrl = "https://picsum.photos/400/300?random=63"),
            VideoItem("r15", "一见你就笑：治愈系音乐节目", "杨迪 杨超越 游戏节目 推理游戏 专治不开心的综艺", "", imageUrl = "https://picsum.photos/400/300?random=64")
        )
    }

    // 模拟剧集缩略图
    val episodeThumbnails = remember {
        listOf(
            EpisodeThumbnail("e1", "2025-10-24", "期加更:冯程朗跳 团舞全员尖叫", "https://picsum.photos/200/150?random=40", isVip = true),
            EpisodeThumbnail("e2", "2025-10-29", "第8期上:梦幻联动! 实习生搭档维嘉海涛…", "https://picsum.photos/200/150?random=41", isPlaying = true),
            EpisodeThumbnail("e3", "2025-10-30", "第8期下:枕 维嘉海涛遭三", "https://picsum.photos/200/150?random=42")
        )
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)
    ) {
        // 视频播放区域 (ArkTS Native Component)
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .aspectRatio(16f / 9f)
                .background(Color.Black)
        ) {
            VideoPlayer(
                modifier = Modifier.fillMaxSize(),
                url = "https://media.w3.org/2010/05/sintel/trailer.mp4"
            )

            // 返回按钮
            Icon(
                imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                contentDescription = "返回",
                tint = Color.White,
                modifier = Modifier
                    .padding(16.dp)
                    .size(24.dp)
                    .clickable { onBack() }
            )
        }

        // 详情内容
        Column(modifier = Modifier.fillMaxSize()) {
            // 选项卡
            TabRow(
                selectedTabIndex = selectedTab,
                backgroundColor = Color.White,
                contentColor = Color.Black,
                indicator = { tabPositions ->
                    TabRowDefaults.Indicator(
                        Modifier.tabIndicatorOffset(tabPositions[selectedTab]),
                        color = Color(0xFFFF6600)
                    )
                }
            ) {
                tabs.forEachIndexed { index, title ->
                    Tab(
                        selected = selectedTab == index,
                        onClick = { selectedTab = index },
                        text = {
                            Row(verticalAlignment = Alignment.CenterVertically) {
                                Text(
                                    text = title,
                                    fontSize = if (selectedTab == index) 18.sp else 16.sp,
                                    fontWeight = if (selectedTab == index) FontWeight.Bold else FontWeight.Normal
                                )
                                if (title == "讨论" && index == 1) {
                                    Spacer(modifier = Modifier.width(4.dp))
                                    Text(
                                        text = "452万+",
                                        fontSize = 12.sp,
                                        color = Color.Red
                                    )
                                }
                            }
                        }
                    )
                }
            }

            LazyColumn(
                modifier = Modifier.fillMaxSize()
            ) {
                item {
                    VideoInfoSection(video)
                }

                item {
                    ActionButtonsSection()
                }

                item {
                    SeasonSelector(
                        seasons = seasons,
                        selectedSeason = selectedSeason,
                        onSeasonSelected = { selectedSeason = it }
                    )
                }

                item {
                    ViewModeSelector(
                        viewModes = viewModes,
                        selectedViewMode = selectedViewMode,
                        onViewModeSelected = { selectedViewMode = it }
                    )
                }

                item {
                    EpisodeThumbnailGrid(
                        thumbnails = episodeThumbnails,
                        modifier = Modifier.fillMaxWidth()
                    )
                }

                item {
                    Divider(thickness = 8.dp, color = Color(0xFFF5F5F5))
                }

                item {
                    Text(
                        text = "为您推荐",
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold,
                        modifier = Modifier.padding(16.dp)
                    )
                }

                // 推荐列表
                items(recommendations) { item ->
                    RecommendationItem(item)
                }
            }

            // 底部标签栏
            BottomTabBar(
                tabs = bottomTabs,
                selectedTab = selectedBottomTab,
                onTabSelected = { selectedBottomTab = it },
                modifier = Modifier.fillMaxWidth()
            )
        }
    }
}

@Composable
private fun VideoInfoSection(video: VideoItem) {
    Column(
        modifier = Modifier.padding(16.dp)
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween,
            modifier = Modifier.fillMaxWidth()
        ) {
            Column(modifier = Modifier.weight(1f)) {
                Text(
                    text = video.title,
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Bold
                )
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = "简介 >",
                    fontSize = 14.sp,
                    color = Color.Gray,
                    modifier = Modifier.clickable { }
                )
                Spacer(modifier = Modifier.height(8.dp))
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Text(
                        text = "${video.rating ?: 9.4}分",
                        fontSize = 14.sp,
                        color = Color(0xFFFF6600),
                        fontWeight = FontWeight.Bold
                    )
                    Spacer(modifier = Modifier.width(12.dp))
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Icon(
                            imageVector = Icons.Default.Favorite,
                            contentDescription = null,
                            modifier = Modifier.size(16.dp),
                            tint = Color.Red
                        )
                        Spacer(modifier = Modifier.width(4.dp))
                        Text(
                            text = "13968",
                            fontSize = 12.sp,
                            color = Color.Black
                        )
                    }
                    Spacer(modifier = Modifier.width(12.dp))
                    Text(
                        text = "职场综艺榜第1名",
                        fontSize = 12.sp,
                        color = Color.Gray
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = "职场节目",
                        fontSize = 12.sp,
                        color = Color.Gray
                    )
                }
            }
        }
    }
}

@Composable
private fun ActionButtonsSection() {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 8.dp),
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        ActionButton(icon = Icons.Default.ThumbUp, text = "推荐")
        ActionButton(icon = Icons.Default.Add, text = "加追")
        ActionButton(icon = Icons.Default.Favorite, text = "下载")
        ActionButton(icon = Icons.Default.Share, text = "投屏")
        ActionButton(icon = Icons.Default.Favorite, text = "一起看")
    }
}

@Composable
private fun ActionButton(icon: ImageVector, text: String) {
    Column(horizontalAlignment = Alignment.CenterHorizontally) {
        Icon(
            imageVector = icon,
            contentDescription = text,
            modifier = Modifier.size(24.dp),
            tint = Color.Black
        )
        Spacer(modifier = Modifier.height(4.dp))
        Text(
            text = text,
            fontSize = 12.sp,
            color = Color.Gray
        )
    }
}

@Composable
private fun SeasonSelector(
    seasons: List<String>,
    selectedSeason: String,
    onSeasonSelected: (String) -> Unit
) {
    Column(modifier = Modifier.padding(vertical = 8.dp)) {
        LazyRow(
            horizontalArrangement = Arrangement.spacedBy(12.dp),
            contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 16.dp)
        ) {
            items(seasons) { season ->
                Text(
                    text = season,
                    fontSize = 14.sp,
                    fontWeight = if (season == selectedSeason) FontWeight.Bold else FontWeight.Normal,
                    color = if (season == selectedSeason) Color(0xFFFF6600) else Color.Black,
                    modifier = Modifier
                        .clickable { onSeasonSelected(season) }
                        .padding(vertical = 8.dp, horizontal = 4.dp)
                        .then(
                            if (season == selectedSeason) {
                                Modifier.border(
                                    1.dp,
                                    Color(0xFFFF6600),
                                    RoundedCornerShape(4.dp)
                                )
                            } else Modifier
                        )
                )
            }
        }
    }
}

@Composable
private fun ViewModeSelector(
    viewModes: List<String>,
    selectedViewMode: String,
    onViewModeSelected: (String) -> Unit
) {
    Column(modifier = Modifier.padding(vertical = 8.dp)) {
        LazyRow(
            horizontalArrangement = Arrangement.spacedBy(8.dp),
            contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 16.dp)
        ) {
            items(viewModes) { mode ->
                Box(
                    modifier = Modifier
                        .clip(RoundedCornerShape(4.dp))
                        .clickable { onViewModeSelected(mode) }
                        .background(
                            color = if (mode == selectedViewMode) Color(0xFFE6F3FF) else Color.Transparent,
                            shape = RoundedCornerShape(4.dp)
                        )
                        .padding(horizontal = 12.dp, vertical = 6.dp)
                ) {
                    Text(
                        text = mode,
                        fontSize = 14.sp,
                        fontWeight = if (mode == selectedViewMode) FontWeight.Bold else FontWeight.Normal,
                        color = if (mode == selectedViewMode) Color(0xFFFF6600) else Color.Black
                    )
                }
            }
        }
    }
}

@Composable
private fun EpisodeThumbnailGrid(
    thumbnails: List<EpisodeThumbnail>,
    modifier: Modifier = Modifier
) {
    Column(modifier = modifier.padding(vertical = 16.dp)) {
        LazyRow(
            horizontalArrangement = Arrangement.spacedBy(12.dp),
            contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 16.dp)
        ) {
            items(thumbnails) { thumbnail ->
                EpisodeThumbnailCard(thumbnail)
            }
        }
    }
}

@Composable
private fun EpisodeThumbnailCard(thumbnail: EpisodeThumbnail) {
    Column(modifier = Modifier.width(140.dp)) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .aspectRatio(16f / 9f)
                .clip(RoundedCornerShape(4.dp))
                .background(Color.LightGray)
        ) {
            NetworkImage(
                imageUrl = thumbnail.imageUrl,
                contentDescription = null,
                contentScale = ContentScale.Crop,
                modifier = Modifier.fillMaxSize()
            )

            if (thumbnail.isVip) {
                Box(
                    modifier = Modifier
                        .align(Alignment.TopEnd)
                        .clip(RoundedCornerShape(0.dp, 4.dp, 0.dp, 4.dp))
                        .background(Color(0xFFFFD700), RoundedCornerShape(0.dp, 4.dp, 0.dp, 4.dp))
                        .padding(horizontal = 4.dp, vertical = 2.dp)
                ) {
                    Text("VIP", fontSize = 10.sp, color = Color.White, fontWeight = FontWeight.Bold)
                }
            }

            if (thumbnail.isPlaying) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(Color.Black.copy(alpha = 0.3f)),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "正在播放",
                        fontSize = 14.sp,
                        color = Color.White,
                        fontWeight = FontWeight.Bold
                    )
                }
            }
        }

        Spacer(modifier = Modifier.height(8.dp))

        Text(
            text = thumbnail.date,
            fontSize = 12.sp,
            color = Color.Gray
        )

        Spacer(modifier = Modifier.height(4.dp))

        Text(
            text = thumbnail.title,
            fontSize = 14.sp,
            color = Color.Black,
            maxLines = 2
        )
    }
}

@Composable
private fun RecommendationItem(video: VideoItem) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp)
            .height(100.dp) // 增加高度以容纳更多文本
            .clickable { }
    ) {
        // 视频封面
        Box(
            modifier = Modifier
                .width(140.dp)
                .fillMaxHeight()
                .clip(RoundedCornerShape(4.dp))
                .background(Color.LightGray)
        ) {
            NetworkImage(
                imageUrl = video.imageUrl,
                contentDescription = null,
                contentScale = ContentScale.Crop,
                modifier = Modifier.fillMaxSize()
            )
        }

        Spacer(modifier = Modifier.width(12.dp))

        Column(modifier = Modifier.weight(1f)) {
            Text(
                text = video.title,
                fontSize = 16.sp,
                fontWeight = FontWeight.Medium,
                maxLines = 2
            )
            Spacer(modifier = Modifier.height(6.dp))
            Text(
                text = video.subtitle.ifEmpty { "精彩推荐：这是一段精彩的推荐内容，值得您花时间观看" },
                fontSize = 12.sp,
                color = Color.Gray,
                maxLines = 3, // 增加到3行
                lineHeight = 16.sp // 设置行高
            )
        }
    }
}

@Composable
private fun BottomTabBar(
    tabs: List<String>,
    selectedTab: String,
    onTabSelected: (String) -> Unit,
    modifier: Modifier = Modifier
) {
    Row(
        modifier = modifier
            .height(50.dp)
            .background(Color.White)
            .padding(horizontal = 16.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        tabs.forEach { tab ->
            Text(
                text = tab,
                fontSize = 14.sp,
                fontWeight = if (tab == selectedTab) FontWeight.Bold else FontWeight.Normal,
                color = if (tab == selectedTab) Color(0xFFFF6600) else Color.Gray,
                modifier = Modifier
                    .clickable { onTabSelected(tab) }
                    .padding(horizontal = 12.dp, vertical = 8.dp)
            )
        }
        Icon(
            imageVector = Icons.Default.Share,
            contentDescription = "更多",
            modifier = Modifier
                .size(20.dp)
                .clickable { },
            tint = Color.Gray
        )
    }
}

